/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.bank.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.bank.entity.TmCustomer;
import org.springblade.modules.bank.entity.TmCustomerLog;
import org.springblade.modules.bank.entity.TmVisitTaskCustomer;
import org.springblade.modules.bank.service.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.bank.entity.TmCustomerAll;
import org.springblade.modules.bank.vo.TmCustomerAllVO;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.springblade.modules.bank.constant.BankConstant.EX1_TYPE_DAILY;
import static org.springblade.modules.bank.constant.BankConstant.EX1_TYPE_INTRODUCE;

/**
 *  控制器
 *
 * @author Blade
 * @since 2023-09-24
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tmcustomerall")
@Api(value = "", tags = "接口")
public class TmCustomerAllController extends BladeController {

	private ITmCustomerAllService tmCustomerAllService;

	private ITmCustomerService iTmCustomerService;

	private ITmCustomerLogService tmCustomerLogService;

	private ITmVisitTaskCustomerService tmVisitTaskCustomerService;

	private ITmCustomerCallRecordService tmCustomerCallRecordService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入tmCustomerAll")
	public R<TmCustomerAll> detail(TmCustomerAll tmCustomerAll) {
		TmCustomerAll detail = tmCustomerAllService.getOne(Condition.getQueryWrapper(tmCustomerAll));
		return R.data(detail);
	}

	/**
	 * 详情
	 */
	@GetMapping("/getAllData")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入tmCustomerAll")
	public R getAllData(TmCustomerAll tmCustomerAll) {
//		try {
//			// 接口地址
//			String restUrl = "https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&ext=&cityid=&city=";
//
//			// 添加身份验证
//			CredentialsProvider provider = new BasicCredentialsProvider();
//			UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
//			provider.setCredentials(AuthScope.ANY, credentials);
//
//			// 创建HttpClient并构造请求
//			HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCredentialsProvider(provider);
//			HttpGet request = new HttpGet(restUrl);
//
//			// 执行请求并读取响应
//			HttpResponse response = builder.build().execute(request);
//			String responseBody = EntityUtils.toString(response.getEntity());
//
//			// 输出响应
//			System.out.println(responseBody);
//
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

		List<TmCustomer> list = iTmCustomerService.list();
		List cList = new ArrayList<TmCustomerAll>();
		list.forEach(item->{
			TmCustomerAll temp = new TmCustomerAll();
			temp.setCustomerCode(item.getCustomerCode());
			temp.setCustMgr(item.getCustMgr());
			temp.setCustMgrName(item.getCustMgrName());
			cList.add(temp);
		});
		tmCustomerAllService.saveBatch(cList);
		return R.data(true);
	}

	/**
	 * 分页 
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入tmCustomerAll")
	public R<IPage<TmCustomerAll>> list(TmCustomerAll tmCustomerAll, Query query) {
		IPage<TmCustomerAll> pages = tmCustomerAllService.page(Condition.getPage(query), Condition.getQueryWrapper(tmCustomerAll));
		return R.data(pages);
	}

	/**
	 * 自定义分页 
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入tmCustomerAll")
	public R<IPage<TmCustomerAllVO>> page(TmCustomerAllVO tmCustomerAll, Query query) {
		IPage<TmCustomerAllVO> pages = tmCustomerAllService.selectTmCustomerAllPage(Condition.getPage(query), tmCustomerAll);
		return R.data(pages);
	}

	/**
	 * 新增 
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入tmCustomerAll")
	public R save(@Valid @RequestBody TmCustomerAll tmCustomerAll) {
		return R.status(tmCustomerAllService.save(tmCustomerAll));
	}

	/**
	 * 修改 
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入tmCustomerAll")
	public R update(@Valid @RequestBody TmCustomerAll tmCustomerAll) {
		return R.status(tmCustomerAllService.updateById(tmCustomerAll));
	}

	/**
	 * 新增或修改 
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入tmCustomerAll")
	public R submit(@Valid @RequestBody TmCustomerAll tmCustomerAll) {
		return R.status(tmCustomerAllService.saveOrUpdate(tmCustomerAll));
	}

	
	/**
	 * 删除 
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(tmCustomerAllService.removeByIds(Func.toLongList(ids)));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/oneKeyIntroduce")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入tmCustomerAll")
	@Transactional(rollbackFor = Exception.class)
	public R oneKeyIntroduce(@Valid @RequestBody TmCustomerAll tmCustomerAll) {
		List<TmCustomerAll> list = tmCustomerAllService.list(new LambdaQueryWrapper<TmCustomerAll>().eq(TmCustomerAll::getCustomerCode,tmCustomerAll.getCustomerCode()));
		if (list.size()>0){
			TmCustomerAll temp = list.get(0);
			List<TmCustomer> tmCustomerList = iTmCustomerService.list(new LambdaQueryWrapper<TmCustomer>().eq(TmCustomer::getCustomerCode,tmCustomerAll.getCustomerCode()));
			if (tmCustomerList.size()>0){
				TmCustomer tmCustomer = tmCustomerList.get(0);
				//管户关系调整记录
				TmCustomerLog tmCustomerLog = new TmCustomerLog();
				//原客户经理信息
				tmCustomerLog.setOriSubBranchCode(tmCustomer.getDeptId());
				tmCustomerLog.setOriSubBranchName(tmCustomer.getDeptName());
				tmCustomerLog.setOriCustMgr(tmCustomer.getCustMgr());
				tmCustomerLog.setOriCustMgrName(tmCustomer.getCustMgrName());

				tmCustomerLog.setSubBranchCode(temp.getDeptId());
				tmCustomerLog.setSubBranchName(temp.getDeptName());
				tmCustomerLog.setCustomerCode(tmCustomer.getCustomerCode());
				tmCustomerLog.setCustomerName(tmCustomer.getCustomerName());
				tmCustomerLog.setCustMgr(temp.getCustMgr());
				tmCustomerLog.setCustMgrName(temp.getCustMgrName());
				tmCustomerLog.setOperateDesc("调整客户经理[一键转介]");
				tmCustomerLogService.save(tmCustomerLog);
				//转介客户的支行以及客户经理
				tmCustomer.setDeptId(temp.getDeptId());
				tmCustomer.setDeptName(temp.getDeptName());
				tmCustomer.setCustMgr(temp.getCustMgr());
				tmCustomer.setCustMgrName(temp.getCustMgrName());
				iTmCustomerService.updateById(tmCustomer);

				//生成转介任务
				TmVisitTaskCustomer taskCustomer=new TmVisitTaskCustomer();
				taskCustomer.setTaskId(9999999999L);
				taskCustomer.setDeptId(Long.valueOf(tmCustomer.getDeptId()));
				taskCustomer.setDeptName(tmCustomer.getDeptName());
				taskCustomer.setCustMgr(tmCustomer.getCustMgr());
				taskCustomer.setCustMgrName(tmCustomer.getCustMgrName());
				taskCustomer.setCustomerCode(tmCustomer.getCustomerCode());
				taskCustomer.setCustomerPhone(tmCustomer.getCustomerTel());
				taskCustomer.setSex(tmCustomer.getSex());
				taskCustomer.setVisitStatus("0");
				//转介任务
				taskCustomer.setEx2(EX1_TYPE_INTRODUCE);
				tmVisitTaskCustomerService.save(taskCustomer);
				//记录转介任务id
				tmCustomerLog.setIntroduceTaskId(taskCustomer.getId());
				//用日志类型记录下当前日志为转介任务的日志  1：转介
				tmCustomerLog.setLogType(1);
				tmCustomerLogService.updateById(tmCustomerLog);
				return R.data(true);
			}
		}
		return R.data(false);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/checkIntroduceExist")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入tmCustomerAll")
	@Transactional(rollbackFor = Exception.class)
	public R checkIntroduceExist(@Valid @RequestBody TmCustomerAll tmCustomerAll) {
		String sql = "select concat(count(*),'') ct from tm_customer_log t where t.customer_code='"+tmCustomerAll.getCustomerCode()+"' and t.log_type=1 and date(t.create_time)=date(sysdate())";
		List<Map> list = tmCustomerCallRecordService.queryBySql(sql);
		if (list.size()>0){
			String ct = list.get(0).get("ct").toString();
			if (!"0".equals(ct)){
				return R.data(true);
			}
		}
		return R.data(false);
	}
}
